package JaggSoft;

import JaggSoft.Utilidades.*;
import java.awt.*;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;

public class ReporteProductoMasMenosSolicitado extends javax.swing.JInternalFrame {
    private JDatePickerImpl selector_fecha_inicial,selector_fecha_final;
    private JCheckBox jchkFechaInicio,jchkFechaFinal;
    private JFileChooser selector;
    public ReporteProductoMasMenosSolicitado() {
        initComponents();
        this.setLocation(new Point(70, 0));
        selector=new JFileChooser();
        selector.setFileFilter(new FileNameExtensionFilter("Libro de Excel",new String[]{"xls","xlsx"}));
        selector.setMultiSelectionEnabled(false);
        selector.setSelectedFile(new File("productos_mas_o_menos_solicitado.xls"));
        jchkFechaInicio=new JCheckBox("");
        jchkFechaFinal=new JCheckBox("");
        jchkFechaInicio.setToolTipText("Incluir");
        jchkFechaFinal.setToolTipText("Incluir");
        selector_fecha_inicial = Util.ColocarSelectorFecha(jpFechaInicial, null,new Component[]{jchkFechaInicio});
        selector_fecha_final = Util.ColocarSelectorFecha(jpFechaFinal, null,new Component[]{jchkFechaFinal});
        CargarDatos("");
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtblProductoMasMenosSolicitado = new javax.swing.JTable();
        jbtnBuscar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jrbDescendente = new javax.swing.JRadioButton();
        jrbAscendente = new javax.swing.JRadioButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jpFechaInicial = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jpFechaFinal = new javax.swing.JPanel();
        jbtnExportar = new javax.swing.JButton();

        setClosable(true);
        setTitle("Producto Mas/Menos Solicitado");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/reporte_masmenos_solicitado.png"))); // NOI18N
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentMoved(java.awt.event.ComponentEvent evt) {
                formComponentMoved(evt);
            }
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jScrollPane1.setViewportView(jtblProductoMasMenosSolicitado);

        jbtnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_buscar_mini.png"))); // NOI18N
        jbtnBuscar.setToolTipText("Buscar");
        jbtnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnBuscarActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Orden"));

        jrbDescendente.setSelected(true);
        jrbDescendente.setText("Descendente");
        jrbDescendente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbDescendenteActionPerformed(evt);
            }
        });

        jrbAscendente.setText("Ascendente");
        jrbAscendente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbAscendenteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jrbDescendente)
                    .addComponent(jrbAscendente))
                .addContainerGap(107, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jrbDescendente)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jrbAscendente)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Fecha"));

        jLabel3.setText("Inicial:");

        javax.swing.GroupLayout jpFechaInicialLayout = new javax.swing.GroupLayout(jpFechaInicial);
        jpFechaInicial.setLayout(jpFechaInicialLayout);
        jpFechaInicialLayout.setHorizontalGroup(
            jpFechaInicialLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 168, Short.MAX_VALUE)
        );
        jpFechaInicialLayout.setVerticalGroup(
            jpFechaInicialLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 23, Short.MAX_VALUE)
        );

        jLabel4.setText("Final:");

        javax.swing.GroupLayout jpFechaFinalLayout = new javax.swing.GroupLayout(jpFechaFinal);
        jpFechaFinal.setLayout(jpFechaFinalLayout);
        jpFechaFinalLayout.setHorizontalGroup(
            jpFechaFinalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 168, Short.MAX_VALUE)
        );
        jpFechaFinalLayout.setVerticalGroup(
            jpFechaFinalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 23, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addComponent(jpFechaInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jpFechaFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(54, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpFechaInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpFechaFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jbtnExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/excel.png"))); // NOI18N
        jbtnExportar.setToolTipText("Exportar a Excel");
        jbtnExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnExportarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jbtnBuscar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(52, 52, 52)
                        .addComponent(jbtnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void CargarDatos(String filtro){
        String consulta="SELECT CONCAT_WS(' ',p.nombre,i.unidad_medida,i.detalle) AS producto,SUM(ds.cantidad) AS cantidad FROM detallesolicitud ds "
                +"INNER JOIN inventario i ON ds.id_inventario=i.id_inventario INNER JOIN producto p ON i.id_producto=p.id_producto "
                +filtro+"GROUP BY CONCAT_WS(' ',p.nombre,i.unidad_medida,i.detalle) ORDER BY SUM(ds.cantidad) "+(jrbDescendente.isSelected()?"DESC":"ASC");
        Util.CargarTabla(jtblProductoMasMenosSolicitado,consulta,new String[]{"Producto","Cantidad"});
        Util.AlinearColumnas(jtblProductoMasMenosSolicitado,SwingConstants.CENTER);
    }
    private void formComponentMoved(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentMoved
        if(evt.getComponent().getLocation().x<70)
            evt.getComponent().setLocation(70,evt.getComponent().getLocation().y);
        if(evt.getComponent().getLocation().y<0)
            evt.getComponent().setLocation(evt.getComponent().getLocation().x,0);
    }//GEN-LAST:event_formComponentMoved
    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        if(this.getParent().getWidth()-70<this.getWidth()  && this.isMaximum)
            this.setSize(this.getWidth()-70,this.getHeight());
    }//GEN-LAST:event_formComponentResized
    private void jbtnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnBuscarActionPerformed
        ConsultaFiltrada();
    }//GEN-LAST:event_jbtnBuscarActionPerformed
    private void ConsultaFiltrada(){
        String filtro="";
        if(jchkFechaInicio.isSelected()||jchkFechaFinal.isSelected()){
            SimpleDateFormat formato = new SimpleDateFormat("yyyy/MM/dd");
            if(jchkFechaInicio.isSelected()){
                String fecha_inicio=formato.format((Date)selector_fecha_inicial.getModel().getValue());
                filtro="WHERE ds.id_solicitud IN (SELECT s.id_solicitud FROM solicitud s WHERE s.fecha >= '"+fecha_inicio+"'";
            }
            if(jchkFechaFinal.isSelected()){
                String fecha_final=formato.format((Date)selector_fecha_final.getModel().getValue());
                filtro+=(!filtro.equals("")?" AND s.fecha <= '"+fecha_final+"')":"WHERE ds.id_solicitud IN (SELECT s.id_solicitud FROM solicitud s WHERE s.fecha <= '"+fecha_final+"')");
            }
            else
                filtro+=")";
            formato=null;
        }
        CargarDatos(filtro);
    }
    private void jrbDescendenteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbDescendenteActionPerformed
        jrbAscendente.setSelected(!jrbDescendente.isSelected());
    }//GEN-LAST:event_jrbDescendenteActionPerformed
    private void jrbAscendenteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbAscendenteActionPerformed
        jrbDescendente.setSelected(!jrbAscendente.isSelected());
    }//GEN-LAST:event_jrbAscendenteActionPerformed

    private void jbtnExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnExportarActionPerformed
        if(jtblProductoMasMenosSolicitado.getRowCount()>0){
            if(selector.showSaveDialog(null)==JOptionPane.OK_OPTION){
                try {
                    String ruta=selector.getSelectedFile().getAbsolutePath();
                    if(!ruta.endsWith(".xls"))
                        ruta+=".xls";
                    File archivo_excel=new File(ruta);
                    switch(Util.ExportarExcel(jtblProductoMasMenosSolicitado,archivo_excel,"Productos Mas o Menos Solicitado")){
                        case OK:
                        JOptionPane.showMessageDialog(null,"Archivo Exportado",this.getTitle(),JOptionPane.INFORMATION_MESSAGE);
                        Desktop.getDesktop().open(archivo_excel);
                        break;
                        case CANCELADO:
                        break;
                        case ERROR:
                        JOptionPane.showMessageDialog(null,"No se pudo exportar el archivo","Error",JOptionPane.ERROR_MESSAGE);
                        break;
                    }
                } catch (Exception ex) {System.err.println(ex.getMessage());}
            }
        }
        else
            JOptionPane.showMessageDialog(null,"No hay datos para exportar","Sin Datos",JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_jbtnExportarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtnBuscar;
    private javax.swing.JButton jbtnExportar;
    private javax.swing.JPanel jpFechaFinal;
    private javax.swing.JPanel jpFechaInicial;
    private javax.swing.JRadioButton jrbAscendente;
    private javax.swing.JRadioButton jrbDescendente;
    private javax.swing.JTable jtblProductoMasMenosSolicitado;
    // End of variables declaration//GEN-END:variables
}